package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 10:48 下午 2023/10/18
 * @Modified By:
 */
@Slf4j
@Component
public class ApifoxUtil {

    @Value("${apifoxAPI.url}")
    private String apifoxUrl;

    @Value("${apifoxAPI.token}")
    private String apifoxToken;

    private static final int timeout = 10000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 查询xhs笔记详情
     * https://apifox.com/apidoc/shared-f838d5a6-280a-4dc5-9039-dfc6c55602c4/api-79715600
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        Type type = new TypeToken<XhsAwemeDetailResult>(){}.getType();
        Gson gson = new Gson();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(apifoxUrl).append("/api/open/xhs/note/detail?token=").append(apifoxToken).append("&noteId=").append(noteId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("ApifoxUtil查询xhs作品详情-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    XhsAwemeDetailResult temp = gson.fromJson(responseInner, type);
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("ApifoxUtil.getXhsAwemeDetail(String) error, noteId:{}, error:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId, new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        try {
            result = gson.fromJson(response, type);
        } catch (Exception e) {
            log.error("ApifoxUtil.getXhsAwemeDetail(String) convert error, noteId:{}, error:{}", noteId, e);
        }
        return result;
    }

    public static void main(String[] args) {
        //String response = HttpUtil.get("http://42.194.182.133:5656/api/open/xhs/note/list?token=fef8d77ae16c54b7e1e5a44573bf07c5&userId=5cfbc3f10000000018023ebb");
        String response = HttpUtil.get("http://42.194.182.133:5656/api/open/xhs/note/detail?token=fef8d77ae16c54b7e1e5a44573bf07c5&noteId=660a8f2b000000001b00fd70");
        System.out.println(response);
        Type type = new TypeToken<XhsAwemeDetailResult>(){}.getType();
        Gson gson = new Gson();
        XhsAwemeDetailResult result = gson.fromJson(response, type);
        System.out.println("111");
    }
}
